package com.telecom.sxint.app.core.service.Chatservice;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

public class SpeechTextApi {

    private static final String API_KEY = "mdU63WmBIsWcERhbi57BZ5AB";
    private static final String SECRET_KEY = "uNrVBlQQ7IpuR1xS3cNcmJtYJapXhznv";

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String[] args) throws IOException {
        System.out.println(queryText2Speech("6678e2ea851b3b0001e93921"));
    }

    public static String speech2Text(MultipartFile file) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject params = new JSONObject();
        params.put("format", "wav");
        params.put("rate", 16000);
        params.put("channel", 1);
        params.put("cuid", "UazjE4OE4v8YfyUHnA0l1dIWj1zT4ZCq");
        params.put("token", getAccessToken());
        params.put("dev_pid", 80001);
        params.put("speech", Base64.getEncoder().encodeToString(file.getBytes()));
        params.put("len", file.getSize());
        RequestBody body = RequestBody.create(mediaType, params.toString());
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/pro_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getJSONArray("result").getString(0);
    }

    public static JSONObject createText2Speech(String text) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject params = new JSONObject();
        params.put("text", new String[]{text});
        params.put("format", "mp3-16k");
        params.put("voice", 0);
        params.put("lang", "zh");
        params.put("speed", 5);
        params.put("pitch", 5);
        params.put("volume", 5);
        params.put("enable_subtitle", 0);
        RequestBody body = RequestBody.create(mediaType, params.toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }

    public static JSONObject queryText2Speech(String taskId) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject params = new JSONObject();
        params.put("task_ids", new String[]{taskId});
        RequestBody body = RequestBody.create(mediaType, params.toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    private static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }
}
